import React, { useEffect, useState, useRef } from 'react';
import { View, Text, Button, Image } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import './index.scss';

// 撒花组件 - 高级增强版
const Confetti = () => {
  const [confettiList, setConfettiList] = useState<JSX.Element[]>([]);
  const animationRef = useRef<number>();

  // 生成随机爆炸参数
  const generateExplosionParams = () => {
    const centerX = Math.random() * 100; // 爆炸中心X坐标
    const centerY = -20 - Math.random() * 20; // 爆炸中心Y坐标，在视口上方
    const angle = Math.random() * Math.PI * 2; // 随机角度
    const distance = 30 + Math.random() * 40; // 爆炸距离
    const endX = centerX + Math.cos(angle) * distance; // 最终X坐标
    const endY = centerY + Math.sin(angle) * distance; // 最终Y坐标
    const rotation = Math.random() * 360; // 旋转角度
    
    return {
      centerX,
      centerY,
      endX,
      endY,
      rotation
    };
  };

  useEffect(() => {
    // 生成更丰富的撒花元素
    const colors = ['#FF6B6B', '#4ECDC4', '#FFD166', '#06D6A0', '#118AB2', '#073B4C', '#F72585', '#7209B7', '#4361EE', '#3A0CA3'];
    const shapes = ['circle', 'square', 'triangle', 'star', 'diamond'];
    const animationTypes = ['', 'oscillate', 'strong-oscillate', 'wavy'];
    const rotationTypes = ['', 'spin', 'spin-reverse', 'spin-slow'];
    const confettiElements: JSX.Element[] = [];
    const confettiCount = 200; // 增加数量

    for (let i = 0; i < confettiCount; i++) {
      const color = colors[Math.floor(Math.random() * colors.length)];
      const shape = shapes[Math.floor(Math.random() * shapes.length)];
      const animationType = animationTypes[Math.floor(Math.random() * animationTypes.length)];
      const rotationType = rotationTypes[Math.floor(Math.random() * rotationTypes.length)];
      const isExplosion = Math.random() > 0.7; // 30%概率使用爆炸效果
      
      const left = Math.random() * 100;
      const animationDelay = Math.random() * 5; // 延长动画延迟范围
      const animationDuration = 4 + Math.random() * 6; // 延长动画持续时间
      const size = shape === 'star' ? 10 + Math.random() * 10 : 6 + Math.random() * 8; // 随机大小
      const xOffset = (Math.random() - 0.5) * 150; // 增加X轴偏移范围
      
      // 添加爆炸效果参数
      let explosionParams = {};
      if (isExplosion) {
        const params = generateExplosionParams();
        explosionParams = {
          '--explosion-center-x': `${params.centerX}%`,
          '--explosion-center-y': `${params.centerY}%`,
          '--explosion-offset-x': `${params.endX}%`,
          '--explosion-offset-y': `${params.endY}%`,
          '--explosion-end-x': `${params.endX}%`,
          '--explosion-end-y': `${params.endY}%`,
          '--explosion-rotation': `${params.rotation}deg`,
          '--delay': `${Math.random() * 0.5}s`
        };
      }

      const className = `confetti ${shape} ${animationType} ${rotationType} ${isExplosion ? 'explosion' : ''}`;
      
      // 设置样式
      const styles: React.CSSProperties = {
        left: `${left}%`,
        animationDelay: `${animationDelay}s`,
        animationDuration: `${animationDuration}s`,
        backgroundColor: color,
        width: `${size}px`,
        height: `${size}px`,
        '--x-offset': `${xOffset}rpx`, // CSS变量用于X轴摆动
        '--animation-duration': `${animationDuration}s`, // 动画持续时间变量
        '--rotation-start': `${Math.random() * 360}deg`,
        '--rotation-end': `${Math.random() * 360}deg`
      };
      
      // 对于星形撒花，使用color属性而不是backgroundColor
      if (shape === 'star') {
        styles.color = color;
        styles.backgroundColor = 'transparent';
      }
      
      // 合并爆炸参数
      Object.assign(styles, explosionParams);

      confettiElements.push(
        <View
          key={i}
          className={className}
          style={styles}
        />
      );
    }

    setConfettiList(confettiElements);

    // 循环添加新的撒花 - 增强版
    const addConfettiPeriodically = () => {
      animationRef.current = window.setTimeout(() => {
        const newConfetti = [];
        for (let i = 0; i < 40; i++) { // 增加新撒花数量
          const color = colors[Math.floor(Math.random() * colors.length)];
          const shape = shapes[Math.floor(Math.random() * shapes.length)];
          const animationType = animationTypes[Math.floor(Math.random() * animationTypes.length)];
          const rotationType = rotationTypes[Math.floor(Math.random() * rotationTypes.length)];
          const isExplosion = Math.random() > 0.6; // 40%概率使用爆炸效果
          
          const left = Math.random() * 100;
          const animationDelay = 0;
          const animationDuration = 4 + Math.random() * 6;
          const size = shape === 'star' ? 10 + Math.random() * 10 : 6 + Math.random() * 8;
          const xOffset = (Math.random() - 0.5) * 150;
          
          // 添加爆炸效果参数
          let explosionParams = {};
          if (isExplosion) {
            const params = generateExplosionParams();
            explosionParams = {
              '--explosion-center-x': `${params.centerX}%`,
              '--explosion-center-y': `${params.centerY}%`,
              '--explosion-offset-x': `${params.endX}%`,
              '--explosion-offset-y': `${params.endY}%`,
              '--explosion-end-x': `${params.endX}%`,
              '--explosion-end-y': `${params.endY}%`,
              '--explosion-rotation': `${params.rotation}deg`,
              '--delay': `${Math.random() * 0.5}s`
            };
          }

          const className = `confetti ${shape} ${animationType} ${rotationType} ${isExplosion ? 'explosion' : ''} new-confetti`;
          
          // 设置样式
          const styles: React.CSSProperties = {
            left: `${left}%`,
            animationDelay: `${animationDelay}s`,
            animationDuration: `${animationDuration}s`,
            backgroundColor: color,
            width: `${size}px`,
            height: `${size}px`,
            '--x-offset': `${xOffset}rpx`,
            '--animation-duration': `${animationDuration}s`,
            '--rotation-start': `${Math.random() * 360}deg`,
            '--rotation-end': `${Math.random() * 360}deg`
          };
          
          // 对于星形撒花，使用color属性而不是backgroundColor
          if (shape === 'star') {
            styles.color = color;
            styles.backgroundColor = 'transparent';
          }
          
          // 合并爆炸参数
          Object.assign(styles, explosionParams);

          newConfetti.push(
            <View
              key={`new-${Date.now()}-${i}`}
              className={className}
              style={styles}
            />
          );
        }
        setConfettiList(prev => [...prev, ...newConfetti]);
        addConfettiPeriodically();
      }, 1500); // 每1.5秒添加一次新撒花
    };

    addConfettiPeriodically();

    // 清理定时器
    return () => {
      if (animationRef.current) {
        clearTimeout(animationRef.current);
      }
    };
  }, []);

  return <View className="confetti-container">{confettiList}</View>;
};

// 光环动画组件 - 增强版
const HaloAnimation = () => {
  return (
    <>
      <View className="halo-animation halo-primary"></View>
      <View className="halo-animation halo-secondary"></View>
    </>
  );
};

// 波浪背景动画组件
const WaveAnimation = () => {
  return (
    <View className="wave-container">
      <View className="wave wave-1"></View>
      <View className="wave wave-2"></View>
      <View className="wave wave-3"></View>
    </View>
  );
};

// 粒子背景组件 - 增强版
const ParticleBackground = () => {
  const [particles, setParticles] = useState<JSX.Element[]>([]);

  useEffect(() => {
    // 初始粒子生成
    generateInitialParticles();
    
    // 定期添加新粒子
    const interval = setInterval(() => {
      addNewParticles();
    }, 3000);
    
    return () => clearInterval(interval);
  }, []);
  
  // 生成初始粒子
  const generateInitialParticles = () => {
    const particleElements = [];
    const particleCount = 30;
    const types = ['circle', 'star', 'glow'];
    
    for (let i = 0; i < particleCount; i++) {
      const type = types[Math.floor(Math.random() * types.length)];
      const size = 2 + Math.random() * 6;
      const left = Math.random() * 100;
      const top = Math.random() * 100;
      const opacity = 0.1 + Math.random() * 0.3;
      const animationDuration = 5 + Math.random() * 15;
      const animationDelay = Math.random() * 10;
      
      const className = `particle ${type}`;
      
      const style: React.CSSProperties = {
        width: `${size}px`,
        height: `${size}px`,
        left: `${left}%`,
        top: `${top}%`,
        opacity,
        animationDuration: `${animationDuration}s`,
        animationDelay: `${animationDelay}s`,
        transform: type === 'star' ? `rotate(${Math.random() * 360}deg)` : 'none',
      };
      
      // 为星形添加特殊的旋转动画
      if (type === 'star') {
        style.animation = `particle-float ${animationDuration}s linear infinite, star-spin ${animationDuration * 2}s linear infinite`;
      }
      
      particleElements.push(
        <View
          key={`initial-${i}`}
          className={className}
          style={style}
        />
      );
    }
    
    setParticles(particleElements);
  };
  
  // 添加新粒子
  const addNewParticles = () => {
    const newParticles = [];
    const particleCount = 5;
    const types = ['circle', 'star', 'glow'];
    
    for (let i = 0; i < particleCount; i++) {
      const type = types[Math.floor(Math.random() * types.length)];
      const size = 2 + Math.random() * 6;
      const left = Math.random() * 100;
      const top = Math.random() * 20; // 只在顶部生成
      const opacity = 0.1 + Math.random() * 0.3;
      const animationDuration = 5 + Math.random() * 15;
      
      const className = `particle ${type} new-particle`;
      
      const style: React.CSSProperties = {
        width: `${size}px`,
        height: `${size}px`,
        left: `${left}%`,
        top: `${top}%`,
        opacity,
        animationDuration: `${animationDuration}s`,
        transform: type === 'star' ? `rotate(${Math.random() * 360}deg)` : 'none',
      };
      
      // 为星形添加特殊的旋转动画
      if (type === 'star') {
        style.animation = `particle-float ${animationDuration}s linear infinite, star-spin ${animationDuration * 2}s linear infinite`;
      }
      
      newParticles.push(
        <View
          key={`new-${Date.now()}-${i}`}
          className={className}
          style={style}
        />
      );
    }
    
    setParticles(prev => {
      // 限制总粒子数量
      const maxParticles = 50;
      const combined = [...prev, ...newParticles];
      return combined.slice(-maxParticles);
    });
  };

  return <View className="particle-container">{particles}</View>;
};

// 呼吸灯效果组件
const PulseEffect = () => {
  return <View className="pulse-effect"></View>;
};

const PaymentSuccessPage: React.FC = () => {
  const router = useRouter();
  const [animationState, setAnimationState] = useState({
    showContent: false,
    showTitle: false,
    showSubtitle: false,
    showInfo: false,
    showCard: false,
    showButtons: false,
    iconScaled: false,
  });

  useEffect(() => {
    // 可以在这里处理一些支付成功后的逻辑，比如更新本地缓存的会员状态
    console.log('支付成功页面加载');
    
    // 添加分阶段入场动画序列
    const animationSequence = [
      { prop: 'showContent', delay: 300 },
      { prop: 'iconScaled', delay: 600 },
      { prop: 'showTitle', delay: 1000 },
      { prop: 'showSubtitle', delay: 1200 },
      { prop: 'showInfo', delay: 1400 },
      { prop: 'showCard', delay: 1700 },
      { prop: 'showButtons', delay: 2000 },
    ];
    
    animationSequence.forEach(({ prop, delay }) => {
      setTimeout(() => {
        setAnimationState(prev => ({ ...prev, [prop]: true }));
      }, delay);
    });
  }, []);

  // 处理按钮点击的波纹效果
  const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement>, navigateFunc: () => void) => {
    const button = e.currentTarget;
    const rect = button.getBoundingClientRect();
    const ripple = document.createElement('span');
    
    // 计算波纹位置
    const size = Math.max(rect.width, rect.height);
    const x = e.clientX - rect.left - size / 2;
    const y = e.clientY - rect.top - size / 2;
    
    // 设置波纹样式
    ripple.classList.add('button-ripple');
    ripple.style.width = ripple.style.height = `${size}px`;
    ripple.style.left = `${x}px`;
    ripple.style.top = `${y}px`;
    
    // 添加波纹到按钮
    button.appendChild(ripple);
    
    // 动画结束后移除波纹
    setTimeout(() => {
      ripple.remove();
      // 执行导航
      navigateFunc();
    }, 600);
  };

  // 跳转回首页 - 带动画的导航
  const goToHome = () => {
    // 添加退出动画
    setAnimationState(prev => ({ 
      ...prev, 
      showContent: false, 
      showTitle: false, 
      showSubtitle: false, 
      showInfo: false, 
      showCard: false, 
      showButtons: false 
    }));
    
    // 延迟导航以展示退出动画
    setTimeout(() => {
      Taro.navigateBack({ delta: 2 }); // 返回上两级页面
    }, 300);
  };

  // 查看会员信息 - 带动画的导航
  const viewMemberInfo = () => {
    // 添加退出动画
    setAnimationState(prev => ({ 
      ...prev, 
      showContent: false, 
      showTitle: false, 
      showSubtitle: false, 
      showInfo: false, 
      showCard: false, 
      showButtons: false 
    }));
    
    // 延迟导航以展示退出动画
    setTimeout(() => {
      Taro.navigateTo({ url: '/pages/my/index' });
    }, 300);
  };

  return (
    <View className="payment-success-container animate-in-container">
      {/* 粒子背景 */}
      <ParticleBackground />
      
      {/* 波浪动画背景 */}
      <WaveAnimation />
      
      {/* 撒花特效 */}
      <Confetti />
      
      {/* 主内容容器 */}
      <View className={`success-content ${animationState.showContent ? 'show' : ''}`}>
        {/* 光环动画 */}
        <HaloAnimation />
        
        {/* 成功图标 - 增强版 */}
        <View className="success-icon-wrapper">
          <div className="icon-glow" />
          {/* 装饰环效果 */}
          <div className="icon-ring-1"></div>
          <div className="icon-ring-2"></div>
          {/* 成功图标 - 增强版 */}
        <View className="success-icon-wrapper">
          <div className="icon-glow" />
          {/* 装饰环效果 */}
          <div className="icon-ring-1"></div>
          <div className="icon-ring-2"></div>
          {/* 闪光效果 */}
          <div className="icon-flash"></div>
          <View className="success-icon">
            <View className={`icon-container ${animationState.iconScaled ? 'scaled' : ''}`}>
              <PulseEffect />
              <Text className={`icon ${animationState.iconScaled ? 'bounce' : ''}`}>🎉</Text>
            </View>
          </View>
        </View>
        </View>
        
        {/* 标题和描述 - 带顺序动画 */}
        <View className={`success-title ${animationState.showTitle ? 'animate-in' : ''} animate-title`}>
          <Text>恭喜您！</Text>
        </View>
        <View className={`success-subtitle ${animationState.showSubtitle ? 'animate-in' : ''} animate-description`}>
          <Text>支付成功</Text>
        </View>
        <View className={`success-info ${animationState.showInfo ? 'animate-in' : ''}`}>
          <Text>您已成功开通会员服务</Text>
          <Text className="secondary-text">所有会员权益已立即生效</Text>
        </View>
        
        {/* 会员卡片预览 - 增强动画 */}
        <View className="member-card-wrapper">
          <div className="member-card-shine" />
          <View className={`member-card ${animationState.showCard ? 'show' : ''}`}>
          <View className="card-header">
            <Text className="card-title">尊享会员</Text>
            <View className="vip-badge pulse">
              <Text className="vip-text">VIP</Text>
            </View>
          </View>
          <View className="card-content">
            <View className={`benefit-item ${animationState.showCard ? 'fade-in-1' : ''}`}>
              <Text className="benefit-icon float">✨</Text>
              <Text className="benefit-text">无限次使用所有功能</Text>
            </View>
            <View className={`benefit-item ${animationState.showCard ? 'fade-in-2' : ''}`}>
              <Text className="benefit-icon float">🚀</Text>
              <Text className="benefit-text">优先体验新功能</Text>
            </View>
            <View className={`benefit-item ${animationState.showCard ? 'fade-in-3' : ''}`}>
              <Text className="benefit-icon float">🎁</Text>
              <Text className="benefit-text">专属客服和技术支持</Text>
            </View>
          </View>
        </View>
        
        {/* 操作按钮 - 带悬停和点击动画 */}
        <View className={`action-buttons ${animationState.showButtons ? 'show' : ''}`}>
          <Button 
            className="btn primary animate-button"
            onClick={(e) => handleButtonClick(e, viewMemberInfo)}
            hoverClass="btn-hover"
            style={{ position: 'relative', overflow: 'hidden' }}
          >
            <Text className="btn-text">查看我的会员</Text>
            <View className="btn-ripple"></View>
          </Button>
          <Button 
            className="btn secondary animate-button"
            onClick={(e) => handleButtonClick(e, goToHome)}
            hoverClass="btn-hover"
            style={{ position: 'relative', overflow: 'hidden' }}
          >
            <Text className="btn-text">返回首页</Text>
            <View className="btn-ripple"></View>
          </Button>
        </View>
      </View>
    </View>
  );
};

export default PaymentSuccessPage;